﻿using System.Linq;
using System.Web.Mvc;
using Inovout.Data.Domain;

namespace Inovout.Web.Mvc
{
    public class QueryCriteriaModelBinder : IModelBinder
    {
        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.HttpContext.Request.HttpMethod.ToLower() == "get")
            {
                var filterValueResult = bindingContext.ValueProvider.GetValue(QueryCriteriaHelper.RequestQueryFilterKey);
                var orderValueResult = bindingContext.ValueProvider.GetValue(QueryCriteriaHelper.RequestQueryOrderKey);
                if (filterValueResult == null && orderValueResult == null)
                {
                    return new QueryCriteria();
                }
                else
                {
                    return QueryCriteriaHelper.Parse(bindingContext.ModelType, bindingContext.ValueProvider);
                }
            }
            else
            {
                return ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
            }
        }

        public object BindFilters(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.HttpContext.Request.HttpMethod.ToLower() == "get")
            {
                var filterValueResult = bindingContext.ValueProvider.GetValue(QueryCriteriaHelper.RequestQueryFilterKey);
                if (filterValueResult == null)
                {
                    return new FilterCriteria[0];
                }
                else
                {
                    return QueryCriteriaHelper.Parse(bindingContext.ModelType, bindingContext.ValueProvider).Filters.ToArray();
                }
            }
            else
            {
                return ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
            }
        }

        public object BindOrders(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (controllerContext.HttpContext.Request.HttpMethod.ToLower() == "get")
            {
                var orderValueResult = bindingContext.ValueProvider.GetValue(QueryCriteriaHelper.RequestQueryOrderKey);
                if (orderValueResult == null)
                {
                    return new OrderCriteria[0];
                }
                else
                {
                    return QueryCriteriaHelper.Parse(bindingContext.ModelType, bindingContext.ValueProvider).Orders.ToArray();
                }
            }
            else
            {
                return ModelBinders.Binders.DefaultBinder.BindModel(controllerContext, bindingContext);
            }
        }
    }
}
